package com.atguigu.MyTest;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
public class JDBCTools {
    private static DataSource ds;
    private static ThreadLocal<Connection> th;
    static {
        try {
            Properties pro = new Properties();
            pro.load(JDBCTools.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
            th = new ThreadLocal<Connection>();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static Connection getConnction() throws SQLException {
        Connection conn = th.get();
        if(conn==null){
            conn = ds.getConnection();
            th.set(conn);
        }
        return conn;
    }
    public static void free(){
        Connection conn = th.get();
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
